/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.controller;

import com.legendshop.dao.support.PageSupport;
import com.legendshop.framework.controller.BaseController;
import com.legendshop.oa.constants.FunctionEnum;
import com.legendshop.oa.constants.PathResolver;
import com.legendshop.oa.constants.SysParameterEnum;
import com.legendshop.oa.dto.Select2Dto;
import com.legendshop.oa.dto.UserOverProjectTimeInputDto;
import com.legendshop.oa.dto.WeekLogReport;
import com.legendshop.oa.dto.WeeklyTimeDto;
import com.legendshop.oa.model.AdminUser;
import com.legendshop.oa.model.WeekLog;
import com.legendshop.oa.pages.AdminTilesPage;
import com.legendshop.oa.pages.BackPage;
import com.legendshop.oa.security.UserDetail;
import com.legendshop.oa.security.UserManager;
import com.legendshop.oa.service.TaskEstimateService;
import com.legendshop.oa.service.TaskService;
import com.legendshop.oa.service.WeekLogService;
import com.legendshop.oa.util.PageSupportHelper;
import com.legendshop.oa.util.PropertiesUtil;
import com.legendshop.permission.service.AdminUserService;
import com.legendshop.util.AppUtils;
import com.legendshop.util.DateUtil;
import com.legendshop.util.TimerUtil;
import com.legendshop.util.WeeklyTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

/**
 * The Class WeekLogController
 * 周报控制器
 */
@Controller
@RequestMapping("/admin/weekLog")
public class WeekLogController extends BaseController{
	
    @Autowired
    private WeekLogService weekLogService;
    
    @Autowired
    private TaskEstimateService taskEstimateService;
    
    @Autowired
    private AdminUserService adminUserService;

	@Autowired
	private TaskService taskService;
    
	/**
	 * 周报列表查询
	 */
    @RequestMapping("/query")
    public String query(HttpServletRequest request, HttpServletResponse response, String curPageNO, String userName, Integer year, Integer weekNo) {
    	UserDetail userDetail = UserManager.getUser(request);

    	if(AppUtils.isNotBlank(userName)) {
    		AdminUser adminUser = adminUserService.getAdminUserByUserName(userName);
			request.setAttribute("adminUser", adminUser);
    	}else{
    		//获取当前用户
			AdminUser adminUser = adminUserService.getAdminUserByUserName(userDetail.getUsername());
			AdminUser leader = adminUserService.getAdminUserByUserName(adminUser.getLeader());
			request.setAttribute("leader", leader);
		}
    	
    	WeeklyTimeDto weeklyTimeDto =  null;
    	
    	Date date = new Date();
    	
    	if(year != null && weekNo != null) {
    		weeklyTimeDto = WeeklyTimeUtil.getWeeklyTime(year, weekNo);
    	}else {
    		Calendar cal = Calendar.getInstance();
    		cal.setTime(date);
    		cal.add(Calendar.DATE, -7);
    		
        	weeklyTimeDto = WeeklyTimeUtil.getWeeklyTime(cal.getTime()); //默认减7天, 查上一周的记录
    	}

    	if(AppUtils.isBlank(year)) {
    		year = weeklyTimeDto.getYear();
    	}
    	
    	if(AppUtils.isBlank(weekNo)) {
    		weekNo = weeklyTimeDto.getWeekNo();
    	}

    	//boolean isAdmin = userDetail.hasFunction(FunctionEnum.FUNCTION_VIEW_ALL_DATA);
		boolean isAdmin = true; //开放给所有的人查看周报

		//查询每个周报,查询下属的周报
		PageSupport<WeekLog> ps = weekLogService.getUserWeekLogList(isAdmin, userDetail.getUsername(), curPageNO, userName, year, weekNo);
		PageSupportHelper.savePage(request, ps);

    	//要最后执行
    	request.setAttribute("currentWeekNo", weeklyTimeDto.getWeekNo());
    	if(AppUtils.isBlank(weeklyTimeDto.getYear()) && year != null && year != 0){
			weeklyTimeDto.setYear(year);
		}
    	if(AppUtils.isBlank(weeklyTimeDto.getYear())) {
    		request.setAttribute("toYear", WeeklyTimeUtil.getCurrentYear(date));    
    	}else {
    		request.setAttribute("currentYear", weeklyTimeDto.getYear());    
    		request.setAttribute("toYear", weeklyTimeDto.getYear());
    	}
		

		return PathResolver.getPath(request, response, AdminTilesPage.ADMINUSER_WEEKLY_LIST_PAGE);
    }

	/**
	 * 保存周报
	 */
    @RequestMapping(value = "/save")
    @ResponseBody
    public String save(HttpServletRequest request, HttpServletResponse response, WeekLog weekLog) {
    	UserDetail userDetail = UserManager.getUser(request);
    	String userName = weekLog.getUserName();
    	if(AppUtils.isBlank(userName) || userName.equals("null")) {
    		userName = userDetail.getUsername(); //用自己的名字
    	}else{
    		//判断是否是我的同事
			boolean isMycolleague = weekLogService.isMycolleague(userDetail.getUsername(), userName);
    		if(!isMycolleague && !userDetail.getUsername().equals(userName)){
    			return "不能编辑自己和下属以外的周报";
			}
		}

    	//只有上级或者本人才可以编辑自己的周报


    	int year = weekLog.getYear();
    	int weekNo = weekLog.getWeekNo();//第几周
        //系统工时
        Date startDate = DateUtil.StringToDate(WeeklyTimeUtil.getStartDayOfWeekNo(year, weekNo), "yyyy-MM-dd");
        Date endDate = DateUtil.StringToDate(WeeklyTimeUtil.getEndDayOfWeekNo(year, weekNo), "yyyy-MM-dd");
        
        //最后一天加1
		Calendar cal = Calendar.getInstance();
		cal.setTime(endDate);
		cal.add(Calendar.DATE, 1);
    	
       Long workTime = taskEstimateService.getTaskEstimateHoursByUser(userName, startDate, cal.getTime());//工时
       Long workingHoursPerWeek = PropertiesUtil.getObject(SysParameterEnum.WORKING_HOURS_PER_WEEK, Long.class);
       if(AppUtils.isBlank(workingHoursPerWeek)) {
    	   workingHoursPerWeek = 40l; //默认是40个小时
       }
       if(workTime < workingHoursPerWeek) {
    	   return "TimenotEnough";//工时不足
       }
       
       weekLog.setWorkTime(workTime);
       
       
       //检查每个项目的时长
		List<UserOverProjectTimeInputDto> list = taskEstimateService.isUserOverProjectTimeInput(userName, startDate, cal.getTime());

		if(AppUtils.isNotBlank(list)){
			StringBuffer result = new StringBuffer("工时异常：");
			for (UserOverProjectTimeInputDto dto: list) {
				result.append(dto.getName()).append(" ").append("最多填写时长：").append(dto.getMaxHoursPerweek()).append(",实际填写： ").append(dto.getTotal());
			}
			return result.toString();
		}
    	
    	if(weekLog.getId() != null) {//update
    		WeekLog origin = weekLogService.getWeekLog(weekLog.getId());
    		if(origin != null && origin.getReviewed() == 0) {//还没有通过审核
    			origin.setWorkTime(workTime);
    			origin.setThisWeekLog(weekLog.getThisWeekLog());
    			origin.setNextWeekPlan(weekLog.getNextWeekPlan());
    			origin.setFeedback(weekLog.getFeedback());
    			
    			if(weekLog.getReviewed() != null && weekLog.getReviewed() == 1) {
    				//通过审核
    				origin.setReviewDate(new Date());
    				origin.setReviewed(1);
    				origin.setReviewer(userDetail.getUsername());
    				
    				//同时也把任务都给设置为已经审核
    				taskEstimateService.updateTaskEstimateHoursByUser(userName, startDate, cal.getTime());
    				
    			}
    			
    			weekLogService.saveWeekLog(origin);
            	saveMessage(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("operation.successful"));
            	return "success";
    		}
    		
    		
    	}else {//save
        	weekLog.setUserName(userName);
        	weekLog.setRecDate(new Date());
        	weekLog.setReviewed(0);//刚建立,尚未审核
        	weekLogService.saveWeekLog(weekLog);
        	saveMessage(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("operation.successful"));
        	return "success";
    	}
    	
    	saveError(request, "保存周报失败");
    	return "fail";
        
		
    }

	/**
	 * 删除周报
	 */
    @RequestMapping(value = "/delete/{id}")
    @ResponseBody
    public String delete(HttpServletRequest request, HttpServletResponse response, @PathVariable
    Long id) {
		UserDetail userDetail = UserManager.getUser(request);
		WeekLog weekLog = weekLogService.getWeekLog(id);
		

		if (weekLog != null) {
			if (!UserManager.hasFunction(request, FunctionEnum.FUNCTION_VIEW_ALL_DATA.value())) {
				if(!userDetail.getUsername().equals(weekLog.getUserName())) {//检查权限
					return "fail";
				}
			}
			
			if(weekLog.getReviewed() == 1) {// 周报已经评审过，无法删除
				return "fail"; 
			}
			int deleteResult = weekLogService.deleteWeekLog(weekLog);
			if (deleteResult <=0) {
				return "fail";
			}
		}else {
			return "fail"; 
		}

		return "success";
    }

	/**
	 * 根据Id加载周报
	 */
    @RequestMapping(value = "/load/{id}")
    public String loadById(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
    	UserDetail userDetail = UserManager.getUser(request);

    	//1. 加载日志
        WeekLog weekLog = weekLogService.getWeekLog(id);
        if(weekLog == null) {
        	return PathResolver.getPath(request, response, BackPage.WEEKLOG_EDIT_PAGE);
        }
        //2. 判断是否是我的下级的同事
        boolean isMycolleague = false;
        
        if(!userDetail.getUsername().equals(weekLog.getUserName())) {
        	isMycolleague =  weekLogService.isMycolleague(userDetail.getUsername(), weekLog.getUserName());
        }

        //3. 加载同事
        AdminUser adminUser =  adminUserService.getAdminUserByUserName(weekLog.getUserName());

		//4.加载日志的统计
		List<WeekLogReport> weekLogReportList = weekLogService.getUserWeekLogList(weekLog);
		
		request.setAttribute("userName", adminUser.getName()); //用户名

        request.setAttribute("adminUser", adminUser);
		request.setAttribute("isMycolleague", isMycolleague);
        request.setAttribute("weekLog", weekLog);
		request.setAttribute("weekLogReportList", weekLogReportList);

		//加载我的目标
		int year = weekLog.getYear();
		int weekNo = weekLog.getWeekNo();//第几周
		//系统工时
		Date startDate = DateUtil.StringToDate(WeeklyTimeUtil.getStartDayOfWeekNo(year, weekNo), "yyyy-MM-dd");
		Date endDate = DateUtil.StringToDate(WeeklyTimeUtil.getEndDayOfWeekNo(year, weekNo), "yyyy-MM-dd");

		//最后一天加1
		Calendar cal = Calendar.getInstance();
		cal.setTime(endDate);
		cal.add(Calendar.DATE, 1);


		List<Select2Dto> myTask = taskService.queryMyList(startDate,endDate, adminUser.getName());
		request.setAttribute("myTask", myTask);

        return PathResolver.getPath(request, response, BackPage.WEEKLOG_EDIT_PAGE);
    }
    
   /**
	 * 加载编辑页面
	 * date 日期
	 * userName 指定用户名, 如果没有指定用户名则是当前的用户
	 */
	@RequestMapping(value = "/load")
	public String load(HttpServletRequest request, HttpServletResponse response, String date, String userName) {
    	UserDetail userDetail = UserManager.getUser(request);
    	if(AppUtils.isBlank(userName) || userName.equals("null") || userName.equals("undefined")) {
    		userName = userDetail.getUsername();
    	}
    	Date givenDate = null;//指定日期
    	if(AppUtils.isBlank(date)) {
    		givenDate = new Date();
    	}else {
    		givenDate = TimerUtil.strToDateShort(date);
    	}
    	
    	WeeklyTimeDto weeklyTimeDto = WeeklyTimeUtil.getWeeklyTime(givenDate);
		
        //系统工时
        Date startDate = DateUtil.StringToDate(weeklyTimeDto.getStartDate(), "yyyy-MM-dd");
        Date endDate = DateUtil.StringToDate(weeklyTimeDto.getEndDate(), "yyyy-MM-dd");
        
        //最后一天加1
		Calendar cal = Calendar.getInstance();
		cal.setTime(endDate);
		cal.add(Calendar.DATE, 1);
        Long workTime = taskEstimateService.getTaskEstimateHoursByUser(userName, startDate, cal.getTime());
        weeklyTimeDto.setWorkTime(workTime);
        WeekLog weekLog = weekLogService.getWeekLog(userName, weeklyTimeDto.getYear(),weeklyTimeDto.getWeekNo() );
        if(weekLog == null) {
        	 weekLog = new WeekLog();
            weekLog.setWeekNo(weeklyTimeDto.getWeekNo());
            weekLog.setYear(weeklyTimeDto.getYear());

        }
        weekLog.setStartDate(weeklyTimeDto.getStartDate());
        weekLog.setEndDate(weeklyTimeDto.getEndDate());
        weekLog.setWorkTime(workTime);
        request.setAttribute("weekLog", weekLog);
        request.setAttribute("userName", userName); //用户名
        
        AdminUser adminUser =  adminUserService.getAdminUserByUserName(userName);
        request.setAttribute("adminUser", adminUser);


		List<Select2Dto> myTask = taskService.queryMyList(startDate,endDate, adminUser.getName());
		request.setAttribute("myTask", myTask);

		return PathResolver.getPath(request, response, BackPage.WEEKLOG_EDIT_PAGE);
	}

   /**
	 * 更新编辑页面
	 */
    @RequestMapping(value = "/update")
    public String update(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
        WeekLog weekLog = weekLogService.getWeekLog(id);
		request.setAttribute("weekLog", weekLog);
		return PathResolver.getPath(request, response, BackPage.WEEKLOG_EDIT_PAGE);
    }

}
